//
//  CHBottomSelectView.swift
//  jyzx
//
//  Created by cyptt on 2022/5/11.
//

import UIKit
/*
 contentview 位置
 */
public enum CH_SHEET_LOCAL_TYPE : Int {
    case bottom = 0  //下
    case center = 1 //中间

}


/*
 tile 位置
 */
public enum CH_COMMON_SHEET_LOCAL_TYPE : Int {
    case left = 0  //下
    case center = 1 //中间
    case right = 2 //中间

}

public class CHSheetView: UIView,UITableViewDelegate,UITableViewDataSource {
    private let mwindow:UIWindow = UIApplication.shared.keyWindow!
    var chaImage:UIImage?
    
    private struct myui{
         static let top_h:CGFloat = 60
         static let bottom_h:CGFloat = 60
    }
    private let marginL_R = 20   //距离左右边距
    private let marginL_32 = 32 //距离左边
    private let margin_B = 24    //按钮距离底部边距
    private let DefaultH = 190  //只有按钮 + 标题高度
    private let ITEM_H:CGFloat = 44
    private var maxItem = 8   //默认最多显示8行
    
    private var content_H:CGFloat = 190
    private var tableview_H:CGFloat = 44
    
    private var contentPosition:CH_SHEET_LOCAL_TYPE = .bottom
    
    private var mShowMaxRow:Int = 8
    private let sureBlueColor:UIColor = UIColor.init(red: 56/255.0, green: 119/255.0, blue: 244/255.0, alpha: 1)
    
    private var isHideCancelBtn:Bool = false
    private let CHBottomSelectCellID = "CHBottomSelectCellID"
    private let CHBottomSelectOtherCellID = "CHBottomSelectOtherCellID"
    var dataSourceArr:[Any] = []
    
    var selectClosureB:(( _ model:CHSheetModel?) ->Void)?
    var cancelClosureB:(( _ msg:String) ->Void)?
    override init(frame:CGRect){
        super.init(frame: frame)
        print(frame)
        if frame == CGRect.zero {
            print("进来了")
            self.frame = mwindow.bounds
        
        }else{
         
        }
        
        self.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.3)
        
        self.addSubview(self.contentV)
        self.addSubview(self.bottomSafeView)
    
        self.addSubview(self.tableView)
     
        
    }
    deinit{
        print("CHSheetView---deinit")
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /*
     选择了
     */
    public  func setSureCallBack(closure:@escaping(_ model:CHSheetModel?)-> Void)
    {
        
        self.selectClosureB = closure
    }
    
    /*
     取消
     */
    public   func setCancleCallBack(cancelClosure:((_ msg:String)-> Void)?){
        
        self.cancelClosureB = cancelClosure
        
    }
    /*
     view加载到window 上面
     @param showMaxRow 显示最大的行数，默认是8行
     @param isHideCancel 是否隐藏取消按钮 true 隐藏 false 显示
     */
    public func show(title:String?,contentTitles:[CHSheetModel]?,showMaxRow:Int = 8,position:CH_SHEET_LOCAL_TYPE = .bottom,isHideCancel:Bool = false){
        
        dataSourceArr = contentTitles!
        self.maxItem = showMaxRow
        self.contentPosition = position
        self.isHideCancelBtn = isHideCancel
        
        self.titleL.text = title
        
        var defaultBottomH:CGFloat = myui.bottom_h
        if isHideCancel == true{
            defaultBottomH = 5
            self.cancelBtn.isHidden = true
        }else{
            defaultBottomH = myui.bottom_h
            self.cancelBtn.isHidden = false
        }
        if contentTitles!.count  > maxItem{
            content_H = CGFloat(maxItem) * ITEM_H + myui.top_h + defaultBottomH
            tableview_H = ITEM_H * CGFloat(maxItem)
        }else{
            content_H = CGFloat(contentTitles!.count) * CGFloat(ITEM_H) + myui.top_h + defaultBottomH
            tableview_H = CGFloat(contentTitles!.count) * CGFloat(ITEM_H)
        }
     
       
        let corner: UIRectCorner = [.topLeft, .topRight]
        
        if position == .bottom{
            cornerRadiusView(view: contentV, radius: 10, rect: CGRect.init(x: 0, y: 0, width: self.frame.size.width, height: content_H), corner: corner)
        }else{
            self.contentV.layer.cornerRadius = 10
            self.contentV.layer.masksToBounds = true
        }
    
      
        self.setPosition()
        mwindow.addSubview(self)
        
        
        
    }
    
  
    
    /*
     设置关闭按钮图片
     */
   public func setChaImage(image:UIImage?){
        self.chaImage = image
        self.chaBtn.setImage(image ?? UIImage.init(named: ""), for: UIControl.State.normal)
      
    }
    
    /*
     设置title 位置
     */
    public func setTitlePosition(position:CH_COMMON_SHEET_LOCAL_TYPE){
        
        if position == .center {
            
            self.titleL.textAlignment = .center
            self.titleL.snp.makeConstraints { make in
                make.top.equalTo(self.contentV).offset(20)
                make.centerX.equalTo(self.contentV.snp.centerX)
    
            }
        }else if position == .right{
            self.titleL.textAlignment = .right
            self.titleL.snp.makeConstraints { make in
                make.top.equalTo(self.contentV).offset(20)
                make.right.equalTo(self.chaBtn.snp.left).offset(-5)
    
            }
        }
    }
    
    /*
     取消按钮位置
     */
    public func setCancelPosition(position:CH_COMMON_SHEET_LOCAL_TYPE){
        
        if position == .center {
            
            self.cancelBtn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.center
        }else if position == .right{
            self.cancelBtn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.right
        }
      
    }
    
    /*
     设置title 字体颜色
     */
    public func setTitleColor(color:UIColor){
        self.titleL.textColor = color
    }
    
    /*
     设置字体
     */
    public func setTitleFont(font:UIFont){
        self.titleL.font = font
    }
    
    /*
     设置取消字体颜色
     */
    public func setCancelTitleColor(color:UIColor){
        self.cancelBtn.setTitleColor(color, for: .normal)
    }
    
    /*
     设置取消字体
     */
    public func setCancelFont(font:UIFont){
        self.cancelBtn.titleLabel?.font = font
    }
    func setPosition(){
        
        if self.contentPosition == .bottom{
            self.contentV.snp.makeConstraints { make in
                make.left.equalTo(0)
                make.right.equalTo(0)
                if #available(iOS 11.0, *) {
                    make.bottom.equalTo(self.safeAreaLayoutGuide).offset(0)
                } else {
                    make.bottom.equalTo(self)
                    // Fallback on earlier versions
                }
                make.height.equalTo(content_H)
            }
            self.bottomSafeView.snp.makeConstraints { make in
                make.left.equalTo(0)
                make.right.equalTo(0)
                make.top.equalTo(self.contentV.snp.bottom)
                make.bottom.equalTo(self)
            }
            self.cancelBtn.snp.makeConstraints { make in
                make.left.equalTo(self.contentV).offset(marginL_32)
                if #available(iOS 11.0, *) {
                    make.bottom.equalTo(self.safeAreaLayoutGuide)
                } else {
                    make.bottom.equalTo(self)
                }
                make.right.equalTo(self.contentV).offset(-marginL_32)
                make.height.equalTo(44)
            }
        }else{
            self.contentV.snp.makeConstraints { make in
                make.left.equalTo(marginL_R)
                make.right.equalTo(-marginL_R)
                make.center.equalToSuperview()
                make.height.equalTo(content_H)
            }
            
            self.cancelBtn.snp.makeConstraints { make in
                make.left.equalTo(self.contentV).offset(marginL_32)
                make.bottom.equalTo(self.contentV.snp.bottom).offset(-5)
                make.right.equalTo(self.contentV).offset(-marginL_32)
                make.height.equalTo(44)
            }
        }
       
        
        self.tableView.snp.makeConstraints { make in
            make.left.equalTo(self.contentV).offset(marginL_R)
            make.right.equalTo(self.contentV).offset(-marginL_R)
            make.top.equalTo(self.contentV).offset(60)
            make.height.equalTo(tableview_H)
          
        }
      
        self.titleL.snp.makeConstraints { make in
            make.top.equalTo(self.contentV).offset(20)
            make.left.equalTo(self.contentV).offset(marginL_R)

        }
        self.chaBtn.snp.makeConstraints { make in
            make.centerY.equalTo(self.titleL)
            make.right.equalTo(self.contentV).offset(-marginL_R)
            make.width.height.equalTo(20)
        }
        
      
        
       
     
    }
    
    
    lazy var titleL = {()-> UILabel in
    
        let label:UILabel = UILabel()
        label.text = "标题"
        label.font = UIFont.systemFont(ofSize: 17,weight: UIFont.Weight.bold)
        label.textColor = UIColor.init(red: 35/255.0, green: 41/255.0, blue: 51/255.0, alpha: 1)
   
        return label
    }()
    
    lazy var chaBtn = {()-> UIButton in
        let btn:UIButton =  UIButton.init(type: UIButton.ButtonType.custom)
        btn.setImage(self.chaImage ??  UIImage.init(named: "gray_cha_icon", in: CHBundle.bundle(), compatibleWith: nil), for: UIControl.State.normal)

        btn.addTarget(self, action: #selector(chaBtnClick(btn:)), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    lazy var contentV = {()-> UIView in
    
        let contentV:UIView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Int(self.frame.size.width) , height: DefaultH))
     
   
//        contentV.layer.masksToBounds = true
//        contentV.layer.cornerRadius = 10
        contentV.backgroundColor = UIColor.white
        contentV.addSubview(self.titleL)

        contentV.addSubview(self.chaBtn)
        contentV.addSubview(self.cancelBtn)
      
        return contentV
    }()
    
    lazy var bottomSafeView =  {()-> UIView in
        let view:UIView = UIView.init()
        view.backgroundColor = UIColor.white
        return view
    }()
    
    lazy var cancelBtn = {()->UIButton in
        let btn:UIButton =  UIButton.init(type: UIButton.ButtonType.custom)
        btn.setTitle("取消", for:  UIControl.State.normal)
        btn.setTitleColor(sureBlueColor, for: UIControl.State.normal)
   
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
    
        btn.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
        btn.addTarget(self, action: #selector(cancenBtn(btn:)), for: UIControl.Event.touchUpInside)
     
        return btn
    }()
    
    //MARK: - lazy
    lazy var tableView = {()-> UITableView in
        let tabV = UITableView.init();
        tabV.delegate = self;
        tabV.dataSource = self;
        tabV.backgroundColor = UIColor.clear
        tabV.separatorColor = UIColor.clear
        tabV.showsVerticalScrollIndicator = false
        tabV.showsHorizontalScrollIndicator = false
   
//        tabV.tableHeaderView = self.headerView
//
//        tabV.register(MyCertListCell.self, forCellReuseIdentifier: MyCertListCellID)
      
        return tabV;
    }()
}
//btnclick
extension CHSheetView {
    @objc func chaBtnClick(btn:UIButton){
        self.removeFromSuperview()
        if self.cancelClosureB != nil{
            self.cancelClosureB!("取消了")
        }
    }
    
    /*
     按钮点击事件
     */
    @objc func btnClick(btn:UIButton){
       

      
   
    }
    
    @objc func cancenBtn(btn:UIButton){
        self.removeFromSuperview()
        if self.cancelClosureB != nil{
            self.cancelClosureB!("取消了")
        }
    }
}

extension CHSheetView{
   
     func cornerRadiusView(view:UIView,radius:CGFloat,rect:CGRect,corner:UIRectCorner){
       // 圆角大小
//        let radius: CGFloat = 16;
       // 圆角位置
//        let corner: UIRectCorner = [.topLeft, .bottomLeft]
       //frame可以先计算完成  避免圆角拉伸
//        let rect = CGRect(x: 0, y: 0, width: 84, height: 32)
       let path: UIBezierPath = UIBezierPath(roundedRect: rect, byRoundingCorners: corner, cornerRadii: CGSize(width: radius, height: radius))
       let maskLayer: CAShapeLayer = CAShapeLayer()
       maskLayer.frame = rect;
       maskLayer.path = path.cgPath
       view.layer.mask = maskLayer;
   }
}

public extension CHSheetView{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataSourceArr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model:CHSheetModel = self.dataSourceArr[indexPath.row] as! CHSheetModel
       
        var cell:CHSheetCell? = tableView.dequeueReusableCell(withIdentifier: CHBottomSelectCellID) as? CHSheetCell
        if cell == nil {

            cell = CHSheetCell.init(style: .default, reuseIdentifier:CHBottomSelectCellID )
        }
        cell?.setBottomSelectMolde(model: model)
        return cell!
      
    
      
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let model:CHSheetModel = self.dataSourceArr[indexPath.row] as! CHSheetModel
       
      
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
            self.removeFromSuperview()
            if self.selectClosureB != nil{
                self.selectClosureB!(model)
            }
        }
      
    }
}

